﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using IOP.Extension.DependencyInjection;
using Microsoft.Extensions.Options;
using Silk.NET.Vulkan;

namespace VkSample913
{
    [ModulePriority(ModulePriority.RenderGroup)]
    public class PipelineModule : VulkanModule, IVulkanRenderWapperModule
    {
        public VulkanRenderWapper RenderWapper { get; set; }
        [Autowired]
        private ILogger<PipelineModule> _Logger { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var lDevice = graphicsManager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var presentPass = disapatcher.SwapchainRenderPass;
                var area = RenderWapper.RenderArea;
                var basePath = AppContext.BaseDirectory;

                var camera = graphicsManager.CreateCamera("main", new Vector3(0, 0, 60), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                camera.EncircleForX(Vector3.Zero, -30 * MathF.PI / 180.0f);
                var aspect = (float)area.Width / area.Height;
                camera.SetProjectMatrix(-aspect, 1.0f, 2.0f, 100.0f);
                camera.SetViewport(0, 0, area.Width, area.Height, 0.0f, 1.0f);

                var shaders = Path.Combine(basePath, "Assets", "Shaders", "spv");
                var document = await JsonDocument.ParseAsync(File.OpenRead(Path.Combine(shaders, "Pipeline.json")));
                var pipelineJson = document.RootElement;

                graphicsManager.TryGetRenderGroup("Main", out IRenderGroup group);
                var mainGroup = group as PrimaryVulkanRenderGroup;

                VulkanShaderInfo[] infos = new VulkanSPVShaderInfo[]
                {
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "Vert", new FileInfo(Path.Combine(shaders,"commonTexLightVert.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "Frag", new FileInfo(Path.Combine(shaders, "commonTexLightFrag.spv"))),
                };
                VulkanShaderInfo[] outlineInfos = new VulkanShaderInfo[]
                {
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "OurlineVert", new FileInfo(Path.Combine(shaders, "commonEdgeVert.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "OurlineFrag", new FileInfo(Path.Combine(shaders, "commonEdgeFrag.spv")))
                };
                await Task.WhenAll(infos[0].LoadShader(), infos[1].LoadShader(), outlineInfos[0].LoadShader(), outlineInfos[1].LoadShader());

                var outlinePipeline = graphicsManager.CreateEmptyPipeline("Outline")
                    .BuildPipelineLayoutFromJson(null, pipelineJson.GetProperty("OutlineLayoutCreateOption").GetRawText())
                    .BuildGraphicsPipelineFromJson(presentPass, pipeCache, outlineInfos, pipelineJson.GetProperty("Outline").GetRawText());
                var outlineCommand = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreateSecondaryCommandBuffer();
                var outlineGroup = graphicsManager.CreateSecondaryVulkanRenderGroup("Outline", outlinePipeline)
                    .Binding(mainGroup, outlineCommand, new VulkanSemaphore[0], new VulkanFence[0]);
                outlineGroup.SetCamera(camera);
                outlineGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<OutlineMiddleware>());
                outlineGroup.CreateItemRenderingAction((builder) => builder.UseMiddleware<OutlineItemMiddleware>());

                var pipeline = graphicsManager.CreateEmptyPipeline("Common")
                    .BuildPipelineLayoutFromJson(pipelineJson.GetProperty("DescriptorSetLayoutCreateOptions").GetRawText(),
                    pipelineJson.GetProperty("PipelineLayoutCreateOption").GetRawText())
                    .BuildUniformBuffer(0, 0, 80, SharingMode.Exclusive)
                    .BuildGraphicsPipelineFromJson(presentPass, pipeCache, infos, pipelineJson.GetProperty("Pipeline").GetRawText());
                var sGroup = graphicsManager.CreateSecondaryVulkanRenderGroup("Common", pipeline).Binding(outlineGroup);
                sGroup.SetCamera(camera);
                sGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<Middleware>());
                sGroup.CreateItemRenderingAction((builder) => builder.UseMiddleware<ItemMiddleware>());

                RenderWapper.CreateAndCutScene<Scene>("main", mainGroup, typeof(TransformSystem), typeof(LightSystem));
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
